package sample;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;
import sample.util.Company;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.ResourceBundle;


public class Controller implements Initializable {

    //所有待抽取人员
    private ArrayList<String> users = new Company().getDefaultUser();
    //所有特殊人员
    private ArrayList<String> allSpeacial = new Company().getSpecialUser();
    //所有抽中人员
    private List<ArrayList<String>> allWinner = new ArrayList<>();
    @FXML
    private Button start;
    @FXML
    private TextArea number;
    @FXML
    private Button end;
    @FXML
    private Label text;
    @FXML
    private ListView listView;
    @FXML
    private TabPane tabs;

    private Timeline timeline;
    private int luckUserNum;

    //第几次
    private int time = 0;

    public void showAnim(MouseEvent mouseEvent) { // 点击开始按钮
        luckUserNum = Integer.parseInt(number.getText());
        if (luckUserNum >= users.size()) { // 检查输入数据是否合法
            number.setText("");
            number.setPromptText("输入人数错误");
            return;
        }
        // 禁止该按钮点击事件
        start.setDisable(true);
        end.setDisable(false);
        // 展示抽奖动画
        KeyFrame keyFrame = new KeyFrame(Duration.seconds(0.02), event -> {
            int feed = new Random().nextInt(users.size()) + 1;
            int result = users.size() % feed;
            text.setText(users.get(result));
        });

        timeline = new Timeline(keyFrame);
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
    }

    public void stop(MouseEvent mouseEvent) {
        start.setDisable(false);
        end.setDisable(true);
        timeline.stop();
        ArrayList<String> luckUsers = findWinner(users.size(), luckUserNum);
        users.removeAll(luckUsers);//移除上次抽中人员
        allWinner.add(luckUsers);//只添加10个
        SingleSelectionModel<Tab> selectModel = tabs.getSelectionModel();
        tabs.getTabs().get(time).setDisable(false);
        selectModel.select(time);
        setResult(time);
        time++;
        text.setText("抽取结果");
        if (time == 10) {
            start.setDisable(true);
            text.setText("最多抽取十次");
            number.setText("");
            number.setPromptText("超过最大抽取次数");
        }
    }


    /**
     * 找到幸运人员
     */
    private ArrayList<String> findWinner(int count, int winnerCount) {
        ArrayList<String> winner = new ArrayList();
        //找到特殊人员
        if (null != allSpeacial && allSpeacial.size() > 0) {//有特殊人员
            //判断是否特殊人员大于第一次抽取人数
            if (allSpeacial.size() >= winnerCount) {
                //获取前winnerCount名
                for (int i = 0; i < winnerCount; i++) {
                    winner.add(allSpeacial.get(i));
                }
                //从allSpacial中删除已重中的人
                allSpeacial.removeAll(winner);
            } else {
                int[] ints = randomCommon(0, users.size(), winnerCount - allSpeacial.size());
                for (int i = 0; i < winnerCount-allSpeacial.size(); i++) {
                    winner.add(users.get(ints[i]));
                }
                winner.addAll(allSpeacial);
                allSpeacial.clear();
            }
        } else {//无特殊人员
            int[] ints = randomCommon(0, users.size(), winnerCount);
            for (int i = 0; i < winnerCount; i++) {
                winner.add(users.get(ints[i]));
            }
        }
        return winner;
    }

    /**
     * 随机指定范围内N个不重复的数
     * 最简单最基本的方法
     *
     * @param min 指定范围最小值
     * @param max 指定范围最大值
     * @param n   随机数个数
     */
    private static int[] randomCommon(int min, int max, int n) {
        if (n > (max - min + 1) || max < min) {
            return null;
        }
        int[] result = new int[n];
        int count = 0;
        while (count < n) {
            int num = (int) (Math.random() * (max - min)) + min;
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if (num == result[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                result[count] = num;
                count++;
            }
        }
        return result;
    }

    public void changeHistory(MouseEvent mouseEvent) {
        SingleSelectionModel<Tab> selectionModel = tabs.getSelectionModel();
        int index = selectionModel.getSelectedIndex();
        setResult(index);
    }

    private void setResult(int position) {
        ArrayList<String> winner = allWinner.get(position);
        String[] temp = winner.toArray(new String[]{});
        ObservableList<String> items = FXCollections.observableArrayList(temp);
        listView.setItems(items);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        end.setDisable(true);
        ObservableList<Tab> allTabs = tabs.getTabs();
        for (int i = 0; i < 10; i++) {
            allTabs.get(i).setDisable(true);
        }
    }
}
